package com.sumu.today.models.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sumu.today.models.permission.entity.User;
import com.sumu.today.models.permission.mapper.UserMapper;
import com.sumu.today.models.permission.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sumu.today.models.permission.utils.SSOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.sql.Wrapper;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sumu
 * @since 2021-12-15
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;


    @Override
    public boolean login(User user, HttpServletRequest request) {

        User user1 = userMapper.getUser(user);
        if(user1 == null || !user.getName().equals(user1.getName()) || !user.getPassword().equals(user1.getPassword())) {
            return false;
        } else {
            // 添加缓存和cookie
            String token = UUID.randomUUID().toString();
            Cookie cookie = new Cookie("TOKEN", token);
            cookie.setDomain("127.0.0.1");
            request.getSession().setAttribute("loginUser", user);
            SSOUtils.loginCache.put(token,user1);
            log.info("登录成功: " + user.toString());
        }

        return true;
    }

    @Override
    public boolean register(User user, HttpServletRequest request) {
        user.setCreateTime(new Date().toString());
        boolean save = save(user);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User user1 = userMapper.selectOne(new QueryWrapper<User>().eq("name",user.getName()));
        if (user1 != null) {
            log.info("add: " + user.toString());
            login(user, request);
            return true;
        }

        return false;
    }


}
